﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;
using System.IO;

namespace WpfRenderTargetBitmap
{
    /// <summary>
    /// MainWindow.xaml 的交互逻辑
    /// </summary>
    public partial class MainWindow : Window
    {
        public MainWindow()
        {
            InitializeComponent();

            Loaded += new RoutedEventHandler(MainWindow_Loaded);

        }

        void MainWindow_Loaded(object sender, RoutedEventArgs e)
        {
            RenderTargetBitmap bitmap = new RenderTargetBitmap((int)gd.Width, (int)gd.Height, 96, 96, PixelFormats.Pbgra32);
            bitmap.Render(gd);

            rectangle1.Fill = new ImageBrush(bitmap);
        }

        Stream GetImageFromControl(Control control)
        {
            MemoryStream ms = null;

            DrawingVisual drawingVisual = new DrawingVisual();
            using (DrawingContext context = drawingVisual.RenderOpen())
            {
                VisualBrush brush = new VisualBrush(gd) { Stretch = Stretch.None };
                context.DrawRectangle(brush, null, new Rect(0, 0, gd.Width, gd.Height));
                context.Close();
            }

            //dpi可以自己设定   // 获取dpi方法：PresentationSource.FromVisual(this).CompositionTarget.TransformToDevice
            RenderTargetBitmap bitmap = new RenderTargetBitmap((int)gd.Width, (int)gd.Height, 96, 96, PixelFormats.Pbgra32);
            bitmap.Render(drawingVisual);

            PngBitmapEncoder encode = new PngBitmapEncoder();
            encode.Frames.Add(BitmapFrame.Create(bitmap));
            ms = new MemoryStream();
            encode.Save(ms);

            return ms;
        }
    }
}
